package com.v2future.sjt.collegecheckingattendance.event;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.common.activity.ImageActivity;
import com.v2future.sjt.collegecheckingattendance.common.activity.MipcaActivityCapture;
import com.v2future.sjt.collegecheckingattendance.event.adapter.EventImgGridAdapter;
import com.v2future.sjt.collegecheckingattendance.event.bean.OneEventBean;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.IntentKey;
import com.v2future.sjt.collegecheckingattendance.utils.WidgetUtil;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.GridViewInScroll;

import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by Administrator on 2016/2/15.
 */
public class EventDetailActivity extends MainActivity implements CompoundButton.OnCheckedChangeListener{

    /**
     * 活动实体 数据传递标识
     */
    public static String DATA_EVENT = "event";

    /** 活动信息 */
    public OneEventBean mOneEventBean;

    /**
     * 头像
     */
    ImageView iconIv;
    /** 名字 */
    TextView nameTv;
    /** 学院 */
    TextView collegeTv;
    /** 发布时间 */
    TextView timeTv;
    /** 活动内容 */
    TextView contentTv;
    /** 活动图片 */
    GridViewInScroll imageGv;
    /** 热度 */
    TextView hotTv;
    /** 活动地点 */
    TextView addrTv;
    /** 活动开始时间 */
    TextView startTimeTv;
    /** 主办方 */
    TextView sponsorTv;
    /** 多少人感兴趣 */
    TextView interestingCountTv;
    /**
     * 扫码人数
     */
    TextView scanCountTv;
    /**
     * 参加人数
     */
    TextView joinCountTv;
    /** 感兴趣的人 */
    GridViewInScroll peopleGv;
    /** 立即参见 */
    Button joinBtn;
    /**
     * 参加和点赞
     */
    CheckBox likeCb,goodCb;

    /**
     * 感兴趣layout
     */
    LinearLayout interetLayout;

    @Override
    public void init() {
        mOneEventBean = (OneEventBean) getIntent().getSerializableExtra(DATA_EVENT);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_event_detail);
        setTitleText(getString(R.string.event_detail));
        initTitleBack(null);
        iconIv = (ImageView) findViewById(R.id.iv_icon);
        nameTv = (TextView) findViewById(R.id.tv_name);
        collegeTv = (TextView) findViewById(R.id.tv_college);
        timeTv = (TextView) findViewById(R.id.tv_time);
        contentTv = (TextView) findViewById(R.id.tv_content);
        imageGv = (GridViewInScroll) findViewById(R.id.gv_images);
        hotTv = (TextView) findViewById(R.id.tv_hot);
        addrTv = (TextView) findViewById(R.id.tv_addr);
        startTimeTv = (TextView) findViewById(R.id.tv_start_time);
        sponsorTv = (TextView) findViewById(R.id.tv_sponsor);
        interestingCountTv = (TextView) findViewById(R.id.tv_count);
        scanCountTv = (TextView) findViewById(R.id.tv_scan_count);
        joinCountTv = (TextView) findViewById(R.id.tv_join_count);
        peopleGv = (GridViewInScroll) findViewById(R.id.gv_people);
        joinBtn = (Button) findViewById(R.id.btn_join_now);
        likeCb = (CheckBox) findViewById(R.id.cb_like);
        likeCb.setOnCheckedChangeListener(this);
        goodCb = (CheckBox) findViewById(R.id.cb_good);
        goodCb.setOnCheckedChangeListener(this);
        interetLayout = (LinearLayout) findViewById(R.id.layout_interet);
    }

    @Override
    public void initAfter() {
        //填充数据
        if (null != mOneEventBean) {
            nameTv.setText(mOneEventBean.getUserName());
            if (!TextUtils.isEmpty(mOneEventBean.getSponsor())) {
                collegeTv.setVisibility(View.VISIBLE);
                collegeTv.setText(mOneEventBean.getSponsor());
            }
            else {
                collegeTv.setVisibility(View.GONE);
            }
            //头像
            if (!TextUtils.isEmpty(mOneEventBean.getUserPic())) {
                x.image().bind(iconIv, mOneEventBean.getUserPic(), getCircleImageOptions(50, 50));
            }
            else {
                setDefaultHead(iconIv);
            }
            collegeTv.setText(mOneEventBean.getSponsor());
            timeTv.setText(mOneEventBean.getActionTime());
            contentTv.setText(mOneEventBean.getActionDesc());
            hotTv.setText(mOneEventBean.getFavorateNum());
            WidgetUtil.setText(scanCountTv, mOneEventBean.getAllCheckedNumber());
            WidgetUtil.setText(joinCountTv, mOneEventBean.getAllInvitedNumber());
            //图片
            if (null != mOneEventBean.getImageUrl() && mOneEventBean.getImageUrl().size() > 0) {
                imageGv.setVisibility(View.VISIBLE);
                EventImgGridAdapter imageUrlAdapter = new EventImgGridAdapter(this, mOneEventBean.getImageUrl());
                imageGv.setAdapter(imageUrlAdapter);
                imageGv.setOnItemClickListener(listener);
            }
            addrTv.setText(mOneEventBean.getActionArea());
            startTimeTv.setText(mOneEventBean.getActionTime());
            sponsorTv.setText(mOneEventBean.getSponsor());
//            interestingCountTv.setText(mOneEventBean.getVoteNum()); // 不需要感兴趣的人数量了
        }
        //0 true 表示没有执行过
        boolean isScan = mOneEventBean.getIsCheck().equals("0") ? true : false;
        boolean isInvite = mOneEventBean.getIsInvited().equals("0") ? true : false;
        if (isScan && isInvite) {//未报名 未签到
            joinBtn.setText("立即参加");
            joinBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showLoadingDialog();
                    doGetInvite(mOneEventBean.getPkActionId());
                }
            });
        }
        else if (!isInvite && isScan) {//已报名 未签到
            joinBtn.setText("扫码签到");
            joinBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //转入二维码
                    startActivity(new Intent(EventDetailActivity.this, MipcaActivityCapture.class));
                }
            });
        }
        else {
            joinBtn.setText("扫码签到");
            joinBtn.setEnabled(false);
        }
    }

    AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(EventDetailActivity.this, ImageActivity.class);
            intent.putExtra(ImageActivity.IMAGE_URL, mOneEventBean.getImageUrl().get(position).toString());
            startActivity(intent);
        }
    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String url = intent.getStringExtra(IntentKey.ZXING_URL);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        BaseRequestParams params = new BaseRequestParams(EventDetailActivity.this, url +"&userCode=" + getUserInfo().getData().getUserCode());
        showLoadingDialog();
        NetUtils.doGetRequest(EventDetailActivity.this, params, new NetTaskListener<BaseResponseBean>() {

            @Override
            public void onSuccess(BaseResponseBean result) {
                joinBtn.setEnabled(false);
                showOneBtnDialog("提示", "成功参加", "知道了", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
                joinBtn.setEnabled(false);
            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    /**
     * 点赞
     * @param fkActionId
     */
    public void doGetPraise(String fkActionId){
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.PRAISE));
        params.addQueryStringParameter("fkActionId", fkActionId);
        NetUtils.doGetRequest(this, params, new NetTaskListener<BaseResponseBean>() {
            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(BaseResponseBean result) {
                tip("点赞成功");
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
                goodCb.setChecked(false);
            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    public void doGetInvite(String fkActionId){
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.INVITE));
        params.addQueryStringParameter("fkActionId", fkActionId);
        NetUtils.doGetRequest(this, params, new NetTaskListener<BaseResponseBean>() {
            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(BaseResponseBean result) {
                tip("参加成功");
                joinBtn.setText("扫码签到");
                joinBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //转入二维码
                        startActivity(new Intent(EventDetailActivity.this, MipcaActivityCapture.class));
                    }
                });
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
                likeCb.setChecked(false);
            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    /**
     * Called when the checked state of a compound button has changed.
     *
     * @param buttonView The compound button view whose state has changed.
     * @param isChecked  The new checked state of buttonView.
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!isChecked) return;
        switch (buttonView.getId()) {
            case R.id.cb_good:
                showLoadingDialog();
                doGetPraise(mOneEventBean.getPkActionId());
                break;
            case R.id.cb_like:
                showLoadingDialog();
                doGetInvite(mOneEventBean.getPkActionId());
                break;
        }
    }
}
